package club.samubird.simpledatahandlekit.utils;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import net.sf.cglib.beans.BeanMap;

import java.util.Map;
import java.util.Objects;

/**
 * @author sam
 * @date 2019/6/27 19:43
 * @description 功能描述
 */
public class BeanMapUtils {

	public static Map<String, Object> bean2MapAndFilterNoneProperty(Object obj) {
		Map<String, Object> nonNullParams = Maps.newHashMap();

		Map<String, Object> params = bean2Map(obj);
		params.forEach(
				(k, v) -> {
					if (Objects.nonNull(v)) {
						nonNullParams.put(k, v);
					}
				}
		);
		return nonNullParams;
	}

	public static Map<String, Object> copyMap(Map<String, Object> old) {
		Map<String, Object> newMap = Maps.newHashMap();
		old.forEach(newMap::put);
		return newMap;
	}

	/**
	 * 将对象装换为 map,对象转成 map，key肯定是字符串
	 *
	 * @param obj 转换对象
	 * @return 返回转换后的 map 对象
	 */
	public static Map<String, Object> bean2Map(Object obj) {
		return null == obj ? null : BeanMap.create(obj);
	}

	public static boolean equalsImpl(Object objectA, Object objectB) {
		if (Objects.nonNull(objectA) && Objects.nonNull(objectB)) {
			if (objectA instanceof Map && objectB instanceof Map) {
				if (objectA == objectB) {
					return true;
				} else {
					Map<?, ?> a = (Map<?, ?>) objectA;
					Map<?, ?> b = (Map<?, ?>) objectB;
					return a.entrySet().equals(b.entrySet());
				}
			} else {
				return false;
			}
		} else {
			return false;
		}
	}

	public static boolean hasEmptyPropertiesWithExcludeSome(Object obj, Object... exclude) {
		Map<String, Object> objectMap = bean2Map(obj);
		return MapUtils.hasEmptyPropertiesWithExcludeSome(objectMap, exclude);
	}

	public static <T, R> R convert(T t, Class<R> clazz) {
		String jsonString = JSONObject.toJSONString(t);
		return JSONObject.parseObject(jsonString, clazz);
	}
}
